//
//  XJCmtChargeViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/7/17.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  "缴费"

#import "XJCmtChargeViewController.h"
#import "XJWalletFinanceDetailViewController.h" //
#import "XJWebViewController.h" //

//View
#import "XJCmtChargeMoneyCell.h"
#import "XJCmtChargePayTypeCell.h"
#import "XJCmtChargeSectionHeaderView.h"
#import "XJCmtChargeBottomView.h"

//vendor
#import <AlipaySDK/AlipaySDK.h>

@interface XJCmtChargeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tv;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) XJCmtChargeBottomView *cmtChargeBottomView;

/**标记支付方式*/
@property (nonatomic, strong) XJCmtChargePayTypeModel *selectPayTypeModel;
/**标记充值金额*/
@property (nonatomic, copy) NSString *chargeMoneyStr;

@end

@implementation XJCmtChargeViewController

#pragma mark - 一 lazy
- (UITableView *)tv{
    if (!_tv) {
        _tv = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tv.delegate = self;
        _tv.dataSource = self;
        _tv.scrollEnabled = NO; //不让滚
        
        // 作用:点击tableview空白处回收键盘
        // https://blog.csdn.net/qin_xiaogang/article/details/51900308
        // https://www.jianshu.com/p/ce2594da8b54
        UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTableViewTouchInSide)];
        tableViewGesture.numberOfTapsRequired = 1;
        tableViewGesture.cancelsTouchesInView = NO;
        [_tv addGestureRecognizer:tableViewGesture];
    
        
        NSString *moneyCellClsName  = NSStringFromClass([XJCmtChargeMoneyCell class]);
        NSString *payTypeCellClsName = NSStringFromClass([XJCmtChargePayTypeCell class]);
        
        [_tv registerNib:[UINib nibWithNibName:moneyCellClsName bundle:nil] forCellReuseIdentifier:moneyCellClsName];
        [_tv registerNib:[UINib nibWithNibName:payTypeCellClsName bundle:nil] forCellReuseIdentifier:payTypeCellClsName];
        
        NSString *secClsName =  NSStringFromClass([XJCmtChargeSectionHeaderView class]);
        
        [_tv registerClass:[XJCmtChargeSectionHeaderView class] forHeaderFooterViewReuseIdentifier:secClsName];
        
        _tv.tableFooterView = [UIView new];
    }
    return _tv;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (XJCmtChargeBottomView *)cmtChargeBottomView {
    if (!_cmtChargeBottomView) {
        _cmtChargeBottomView = [[XJCmtChargeBottomView alloc] initWithFrame:CGRectMake(0,KHeight - 130 - kStatusBarAndNavigationBarHeight, KWidth, 130)];
        
        XJWeakSelf(self);
        
        //点击充值协议
        _cmtChargeBottomView.xjcmtChargeBottomViewClickChargeProtocolBlock = ^{
            XJWebViewController *webVC = [[XJWebViewController alloc] init];
            webVC.vcType = XJWebVCTypeChargeProtocol;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        };
        
        //点击确然支付block
        _cmtChargeBottomView.xjcmtChargeBottomViewClickSurePayBtnBlock = ^{
            //处理点击逻辑
            [weakself btnBussinessLogic];
        };
    }
    return _cmtChargeBottomView;
}
#pragma mark - 二 life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUpNav];
    
    self.tv.frame = self.view.bounds;
    [self.view addSubview:self.tv];
    
    [self simulateRequestData];
    
    [self.view addSubview:self.cmtChargeBottomView];
}

- (void)setupUpNav {
    self.navigationItem.title = @"缴费";
    UIButton *rightRecoderBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [rightRecoderBtn setTitle:@"记录" forState:(UIControlStateNormal)];
    [rightRecoderBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [rightRecoderBtn addTarget:self action:@selector(recoderBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightRecoderBtn];
}
- (void)recoderBtnAction:(UIButton *)button {
    XJLog(@"记录");
    
    XJWalletFinanceDetailViewController *vc = [[XJWalletFinanceDetailViewController alloc] init];
    vc.finance_type = @"4"; //缴费明细
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 三 UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSString *moneyCellClsName  = NSStringFromClass([XJCmtChargeMoneyCell class]);
        XJCmtChargeMoneyCell *moneyCell = [tableView dequeueReusableCellWithIdentifier:moneyCellClsName];

        moneyCell.xjcmtChargeCellBlock = ^(NSString *moneyStr) {
            self.chargeMoneyStr = moneyStr;
        };
        
        return moneyCell;
    }else {
    
        NSString *payTypeCellClsName = NSStringFromClass([XJCmtChargePayTypeCell class]);
        XJCmtChargePayTypeCell *payTypeCell = [tableView dequeueReusableCellWithIdentifier:payTypeCellClsName];
        payTypeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        XJCmtChargePayTypeModel *model = self.dataArray[indexPath.row];
        payTypeCell.model = model;

        return payTypeCell;
    }
}
#pragma mark - 三 UITableViewDelegate,

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 100;
    }else{
        return 44;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSArray *secArr = @[@"请输入充值金额",@"请选择付款方式"];
    
    NSString *secClsName =  NSStringFromClass([XJCmtChargeSectionHeaderView class]);

    XJCmtChargeSectionHeaderView *secHv = [tableView dequeueReusableHeaderFooterViewWithIdentifier:secClsName];
    
    [secHv configureXJCmtChargeSectionHeaderViewWithTitle:secArr[section]];
    
    return secHv;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        //全部清空。让后然选中的model处于选中状态
        for (XJCmtChargePayTypeModel *model in self.dataArray) {
            model.isCheck = NO;
        }
        
        XJCmtChargePayTypeModel *currentM = self.dataArray[indexPath.row];
        currentM.isCheck = YES;
        
        self.selectPayTypeModel = currentM;
        
        [self.tv reloadData];
    }
   
    
}
#pragma mark - 四  网络请求x
- (void)simulateRequestData {
//    @property (nonatomic, copy) NSString *iconStr;
//    @property (nonatomic, copy) NSString *payTypeStr;
//    /**是否选中*/

    NSArray *payTypeArr = @[@{@"iconStr":@"pay_alipay",
                              @"payTypeStr":@"支付宝支付"
                              },
                            @{@"iconStr":@"pay_WeChat",
                              @"payTypeStr":@"微信支付"
                              }];
    
    
    for (NSDictionary *tempDic in payTypeArr) {
        XJCmtChargePayTypeModel *model = [XJCmtChargePayTypeModel mj_objectWithKeyValues:tempDic];
        [self.dataArray addObject:model];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tv reloadData];
    });
}

#pragma mark - 五 支付:微信支付、支付宝支付
- (void)requestPayByZFBWithPayDic:(NSDictionary *)payDic  {
    
    [XJHttpTool requestPayWithDic:payDic successH:^(id responseObjc) {
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        XJLog(@"支付：%@",jsonStr);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        //调用支付宝SDK进行支付。
        if ([code isEqualToString:@"0"]) {
            NSString *order_info = responseObjc[@"data"][@"pay"][@"params"][@"order_info"];
            XJLog(@"支付宝参数:%@-%ld",order_info,order_info.length);
            NSString *appScheme = @"com.tzyang.cn.XinJiangMall";
            //        NOTE: 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:order_info fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut = %@",resultDic);
            }];
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        XJLog(@"%@",error);
    }];
}

#pragma mark - 六 private method
//处理点击逻辑
- (void)btnBussinessLogic {
    
    if ([NSString isEmptyString:self.chargeMoneyStr]) {
        [JRToast showWithText:@"未来巴扎:请输入充值金额"];
        return;
    }
    
    if (self.selectPayTypeModel == nil) {
        [JRToast showWithText:@"未来巴扎:请选择支付方式"];
        return;
    }
    
    if ([self.selectPayTypeModel.iconStr isEqualToString:@"pay_alipay"]) {//
        XJLog(@"支付宝支付 %@",self.chargeMoneyStr);
        NSString *channel_id = @"alipay_app";
        NSString *order_type = @"3";
        NSString * order_amount = [NSString stringWithFormat:@"%@",self.chargeMoneyStr];
        NSString *foreign_infos = self.cmtId;
        NSDictionary *zfbPayDic = NSDictionaryOfVariableBindings(channel_id,order_type,order_amount,foreign_infos);
        XJLog(@"支付宝支付请求参数:%@",zfbPayDic);
        
        [self requestPayByZFBWithPayDic:zfbPayDic];
        
    }else {
        XJLog(@"微信支付 %@",self.chargeMoneyStr);
        
        NSString *channel_id = @"weixin_app";
        NSString *order_type = @"3";
        NSString * order_amount = [NSString stringWithFormat:@"%@",self.chargeMoneyStr];
        NSString *foreign_infos = self.cmtId;
        NSDictionary *weiXinPayDic = NSDictionaryOfVariableBindings(channel_id,order_type,order_amount,foreign_infos);
        XJLog(@"微信支付请求参数:%@",weiXinPayDic);
    }
}

#pragma mark - 回收键盘
- (void)commentTableViewTouchInSide {
    [self.tv endEditing:YES];
}

@end
